package me.dengfengdecao.android.photogallery;

import android.net.Uri;
import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

/**
 * 处理网络连接的专用类
 */
public class NetFetcher {

    private static final String TAG = "NetFetcher";
    public static final String PREF_SEARCH_QUERY = "searchQuery";       // 查询字符串key
    public static final String PREF_LAST_RESULT_URL = "lastResultUrl";  // 最近图片所在的网址key

    private static final String ENDPOINT = "http://apis.baidu.com/txapi/mvtp/meinv";    // 请求接口
    private static final String APIKEY = "e612ee80f89bc40a6e189046fec5014a";            // apikey
    private static final String REQUEST_METHOD_GET = "GET";                             // 提交方式
    private static int NUMBER = 10;  // 需要获取的条数 默认获取10条数据

    /**
     * 得到形如:
     *  "newslist": [
     {
     "title": "性感妹子瑞莎Trista粉嫩内衣秀爆乳写真",
     "description": "性感妹子瑞莎Trista粉嫩内衣秀爆乳写真...",
     "picUrl": "http://t1.27270.com/uploads/tu/201508/06/slt.jpg",
     "url": "http://www.27270.com/ent/meinvtupian/2015/123942.html"
     },
     的json数据
     * @param httpUrl 请求接口
     * @return 返回结果
     */
    public String getJsonData(String httpUrl) throws IOException {
        HttpURLConnection connection = null;
        InputStream in = null;
        BufferedReader reader = null;
        StringBuffer stringBuffer = null;
        try {
            stringBuffer = new StringBuffer();
            URL url = new URL(httpUrl);
            connection = (HttpURLConnection) url.openConnection();

            if (connection == null) {
                return null;
            }

            connection.setRequestMethod(REQUEST_METHOD_GET);
            // 填入apikey到HTTP header
            connection.setRequestProperty("apikey", APIKEY);
            connection.connect();

            in = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                stringBuffer.append(strRead);
                stringBuffer.append("\r\n");
            }
            reader.close();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
        return stringBuffer.toString();
    }

    /**
     * 得到缩略图的字节数组
     * @param urlSpec 缩略图的地址
     * @return 返回缩略图的字节数组
     * @throws IOException
     */
    public byte[] getPicUrlBytes(String urlSpec) {
        HttpURLConnection connection = null;
        ByteArrayOutputStream out = null;
        try {
            URL url = new URL(urlSpec);
            connection = (HttpURLConnection)url.openConnection();
            out = new ByteArrayOutputStream();
            InputStream in = connection.getInputStream();

            if (connection.getResponseCode() != HttpURLConnection.HTTP_OK)
                return null;

            int bytesRead;
            byte[] buffer = new byte[1024];
            while ((bytesRead = in.read(buffer)) > 0) {
                out.write(buffer, 0, bytesRead);
            }

            return out.toByteArray();
        } catch (FileNotFoundException e) {
            Log.e(TAG, "getPicUrlBytes 获取缩略图的字节数组失败" + e);
            return null;
        } catch (IOException e) {
          return null;
        } finally {
            if (out != null)
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            if (connection != null)
                connection.disconnect();
        }
    }

	/**
	 * 获取GalleryItem对象
	 * @return 返回GalleryItem对象的集合
	 */
    public ArrayList<GalleryItem> fetchItems() {
        ArrayList<GalleryItem> items = new ArrayList<>();

        String url = Uri.parse(ENDPOINT).buildUpon()
                .appendQueryParameter("num", String.valueOf(NUMBER))
                .build().toString();

	    try {
		    String jsonString = getJsonData(url);
		    Log.d(TAG, "fetchItems 获取到json串:" + jsonString);

		    // 解析JSON数据
            JSONObject json = new JSONObject(jsonString);
            JSONArray jsonArray = json.getJSONArray("newslist");
            for (int i = 0; i < jsonArray.length(); i++) {
                GalleryItem galleryItem = new GalleryItem(jsonArray.getJSONObject(i));
                items.add(galleryItem);
            }

            /* JSONObject json = new JSONObject(jsonString);
		    for (int num = 0;num < NUMBER;num++) {
			    String numStr = String.valueOf(num);
			    if (json.has(numStr)) {
				    GalleryItem galleryItem = new GalleryItem(json.getJSONObject(numStr));
				    items.add(galleryItem);
			    }
		    } */
	    } catch (IOException e) {
		    Log.e(TAG, "获取JSON串失败！" + e);
	    } catch (JSONException e) {
		    Log.e(TAG, "解析JSON文件失败！" + e);
	    }
	    return items;
    }

    public ArrayList<GalleryItem> search(String query) {
        NUMBER = 50;
        ArrayList<GalleryItem> items = fetchItems();
        ArrayList<GalleryItem> newItems = new ArrayList<>();
        for (int i=0;i<items.size();i++) {
            if (items.get(i).getDescription().contains(query)) {
                GalleryItem gi = items.get(i);
                newItems.add(gi);
            }
        }
        NUMBER = 10;
        return newItems;
    }
}
